package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.google.common.collect.Lists;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.RmGame;
import com.ruoyi.web.cp.domain.rm.RmResult;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.mapper.RmGameMapper;
import com.ruoyi.web.mapper.RmResultMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RmobGroup2Service {
    @Autowired
    private RmGameMapper rmGameMapper;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private RmResultMapper rmResultMapper;
    @Autowired
    private ConfigLoader configLoader;

    public void execute(int days, String key) {
        List<RmGame> rmGames = rmGameMapper.selectLastNDays(days);
        List<String> gameIds = rmGames.stream().map(RmGame::getGameId).collect(Collectors.toList());

        List<RmResult> rmResults = rmResultMapper.selectByGameIds(gameIds);
        Map<String, RmResult> gameIdToRmResultMap = rmResults.stream().collect(Collectors.toMap(
                RmResult::getGameId,
                v -> v,
                (existing, replacement) -> existing
        ));

        List<RmGame> list1 = new ArrayList<>();
        List<RmGame> list2 = new ArrayList<>();

        for (RmGame rmGame : rmGames) {
            RmGame.ObDetail obDetail = rmGame.obPlvFromJson();
            if (obDetail == null) {
                continue;
            }
            String allLingPlvTeamA = obDetail.getAll_ling_plv_teamA();//全场零失球-主
            String allLingPlvTeamB = obDetail.getAll_ling_plv_teamB();//全场零失球-客
            String sxLingWinPlvTeamA = obDetail.getSx_ling_win_plv_teamA();//全场零失球获胜-主
            String sxLingWinPlvTeamB = obDetail.getSx_ling_win_plv_teamB();//全场零失球获胜-客

            //1.全场零失球<1.05
            if (StrUtil.isAllNotBlank(allLingPlvTeamA, allLingPlvTeamB)
                    && ((allLingPlvTeamA != null && Double.parseDouble(allLingPlvTeamA) <= 1.05)
                    || (allLingPlvTeamB != null && Double.parseDouble(allLingPlvTeamB) <= 1.05))
            ) {
                list1.add(rmGame);
            }

            //2.全场零失球获胜<1.05
            if (StrUtil.isAllNotBlank(allLingPlvTeamA, allLingPlvTeamB)
                    && ((sxLingWinPlvTeamA != null && Double.parseDouble(sxLingWinPlvTeamA) <= 1.05)
                    || (sxLingWinPlvTeamB != null && Double.parseDouble(sxLingWinPlvTeamB) <= 1.05))
            ) {
                list2.add(rmGame);
            }
        }

        String path = configLoader.getRmPath() + "rmob-group2" + FileSystems.getDefault().getSeparator() + "方案汇总-" + days + "天.xlsx";
        File tempFile = new File(path);
        // 如果文件已存在，先删除
        if (tempFile.exists()) {
            FileUtil.del(tempFile);
        }
        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(tempFile);

        sendList1("方案1", list1, gameIdToRmResultMap, writer);
//        sendList2("方案1-全场零失球获胜<1.05", list2, gameIdToRmResultMap, writer);

        // 关闭流
        writer.close();

        winxinService.sendQlMedia(key, path);
    }

    private String get81To85MinOdds(RmGame rmGame) {
        List<RmGame.Detail> goalTime5Plvs = rmGame.goalTime5PlvFromJson();
        String rm00 = "";
        if (CollUtil.isNotEmpty(goalTime5Plvs)) {
            Map<String, String> allPlvDict = goalTime5Plvs.stream().collect(Collectors.toMap(
                    RmGame.Detail::getScore,
                    RmGame.Detail::getPlv,
                    (existing, replacement) -> existing
            ));
            rm00 = allPlvDict.get("81:00-85:59");
        }
        return rm00;
    }

    private String get00MinOdds(RmGame rmGame) {
        List<RmGame.Detail> allPlv = rmGame.allPlvFromJson();
        String rm00 = "";
        if (CollUtil.isNotEmpty(allPlv)) {
            Map<String, String> allPlvDict = allPlv.stream().collect(Collectors.toMap(
                    RmGame.Detail::getScore,
                    RmGame.Detail::getPlv,
                    (existing, replacement) -> existing
            ));
            rm00 = allPlvDict.get("0-0");
        }
        return rm00;
    }

    public void sendList1(String name, List<RmGame> list1, Map<String, RmResult> gameIdToRmResultMap, ExcelWriter writer) {
        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队", "RM00", "81-85",
//                "全场零失球-主", "全场零失球-客",
                "半场结果", "全场结果", "首进球时间"
        };
        writer.merge(headers.length - 1, name);
        writer.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDoubleMerge 有对应的 getter 方法）
        for (RmGame rmGame : list1) {
            List<String> row = Lists.newArrayList();
            row.add(rmGame.parseDateStr());       // 日期
            row.add(rmGame.getLeague());          // 联赛
            row.add(rmGame.getTeamA());           // 主队
            row.add(rmGame.getTeamB());           // 客队
            row.add(get00MinOdds(rmGame));        //RM00
            row.add(get81To85MinOdds(rmGame));    //RM81-85

            RmGame.ObDetail obPlvs = rmGame.obPlvFromJson();
//            if (obPlvs != null) {
//                String allLingPlvTeamA = obPlvs.getAll_ling_plv_teamA();
//                String allLingPlvTeamB = obPlvs.getAll_ling_plv_teamB();
//                if (allLingPlvTeamA != null && Double.parseDouble(allLingPlvTeamA) <= 1.05) {
//                    row.add(allLingPlvTeamA);
//                } else {
//                    row.add("");
//                }
//                if (allLingPlvTeamB != null && Double.parseDouble(allLingPlvTeamB) <= 1.05) {
//                    row.add(allLingPlvTeamB);
//                } else {
//                    row.add("");
//                }
//            } else {
//                for (int i = 0; i < 2; i++) {
//                    row.add("");
//                }
//            }

            RmResult rmResult = gameIdToRmResultMap.get(rmGame.getGameId());
            if (rmResult != null) {
                row.add(rmResult.getHalfScore());
                row.add(rmResult.getAllScore());
                row.add(rmResult.getGoalTime());
            } else {
                for (int i = 0; i < 3; i++) {
                    row.add("");
                }
            }

            writer.writeRow(row);
        }
        int[] columnWidths = {
                18 * 256, // 日期
                15 * 256, // 联赛
                20 * 256, // 主队
                20 * 256, // 客队
                12 * 256, // RM00
                12 * 256, // RM81-85
//                15 * 256, // 全场零失球-主
//                15 * 256, // 全场零失球-客
                12 * 256, // 半场结果
                12 * 256, // 全场结果
                12 * 256  // 首进球时间
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
    }

    public void sendList2(String name, List<RmGame> list1, Map<String, RmResult> gameIdToRmResultMap, ExcelWriter writer) {
        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队", "RM00", "81-85",
                "全场零失球获胜-主", "全场零失球获胜-客",
                "半场结果", "全场结果", "首进球时间"
        };
        writer.merge(headers.length - 1, name);
        writer.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDoubleMerge 有对应的 getter 方法）
        for (RmGame rmGame : list1) {
            List<String> row = Lists.newArrayList();
            row.add(rmGame.parseDateStr());       // 日期
            row.add(rmGame.getLeague());          // 联赛
            row.add(rmGame.getTeamA());           // 主队
            row.add(rmGame.getTeamB());          // 客队
            row.add(get00MinOdds(rmGame));         //RM00
            row.add(get81To85MinOdds(rmGame));   //RM 81-85

            RmGame.ObDetail obPlvs = rmGame.obPlvFromJson();
            if (obPlvs != null) {
                String sxLingWinPlvTeamA = obPlvs.getSx_ling_win_plv_teamA();
                String sxLingWinPlvTeamB = obPlvs.getSx_ling_win_plv_teamB();
                if (sxLingWinPlvTeamA != null && Double.parseDouble(sxLingWinPlvTeamA) <= 1.05) {
                    row.add(sxLingWinPlvTeamA);
                } else {
                    row.add("");
                }
                if (sxLingWinPlvTeamB != null && Double.parseDouble(sxLingWinPlvTeamB) <= 1.05) {
                    row.add(sxLingWinPlvTeamB);
                } else {
                    row.add("");
                }
            } else {
                for (int i = 0; i < 2; i++) {
                    row.add("");
                }
            }

            RmResult rmResult = gameIdToRmResultMap.get(rmGame.getGameId());
            if (rmResult != null) {
                row.add(rmResult.getHalfScore());
                row.add(rmResult.getAllScore());
                row.add(rmResult.getGoalTime());
            } else {
                for (int i = 0; i < 3; i++) {
                    row.add("");
                }
            }

            writer.writeRow(row);
        }
        int[] columnWidths = {
                18 * 256, // 日期
                15 * 256, // 联赛
                20 * 256, // 主队
                20 * 256, // 客队
                12 * 256, // RM00
                12 * 256, // RM81-85
                15 * 256, // 全场零失球获胜-主
                15 * 256, // 全场零失球获胜-客
                12 * 256, // 半场结果
                12 * 256, // 全场结果
                12 * 256  // 首进球时间
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
    }
}
